package org.ezplatform.office.questionnaire.web.rest;
/** 
* @author 作者: wujs
* @version 创建时间：2018年1月12日 上午8:41:57 
* 类说明 :问卷接口
*/

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.ezplatform.cloud.api.component.popuser.PopUserScopeUtilService;
import org.ezplatform.cloud.api.system.role.RoleApiService;
import org.ezplatform.cloud.api.system.user.UserApiService;
import org.ezplatform.cloud.common.controller.BaseController;
import org.ezplatform.cloud.common.log.LogService;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.office.questionnaire.entity.Questionnaire;
import org.ezplatform.office.questionnaire.entity.QuestionnaireAnswer;
import org.ezplatform.office.questionnaire.entity.QuestionnaireTopic;
import org.ezplatform.office.questionnaire.entity.QuestionnaireTopicOptions;
import org.ezplatform.office.questionnaire.entity.QusetionnaireAnswerStatus;
import org.ezplatform.office.questionnaire.service.QuestionnaireAnswerService;
import org.ezplatform.office.questionnaire.service.QuestionnaireAnswerStatusService;
import org.ezplatform.office.questionnaire.service.QuestionnaireService;
import org.ezplatform.office.questionnaire.service.QuestionnaireTopicOptionsService;
import org.ezplatform.office.questionnaire.service.QuestionnaireTopicService;
import org.ezplatform.office.questionnaire.util.SendMsgUtils;
import org.ezplatform.util.DateUtils;
import org.ezplatform.util.GlobalConstant;
import org.ezplatform.util.JsonUtils;
import org.ezplatform.util.JwtUtils;
import org.ezplatform.util.RestClient;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.UuidUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
  
@RestController("qac")
@RequestMapping("/api/questionnaire")
public class QuestionnaireApiController extends BaseController {
	
	private final static Logger LOG = LoggerFactory.getLogger(QuestionnaireApiController.class);
	
	@Autowired
	private QuestionnaireService questionnaireService;
	
	@Autowired
	private QuestionnaireAnswerStatusService answerStatusService;
	
	@Autowired
	private QuestionnaireAnswerService answerService;
	
//	@Autowired
//	private PopUserScopeUtilService popUserScopeUtilService;
	
	@Autowired
	private QuestionnaireTopicService topicService;
	
	@Autowired
	private QuestionnaireTopicOptionsService optionService;
	
//	@Autowired
//	private DictDetailApiService dictDetailApiService;

	@Autowired
	private UserApiService userApiService;

	@Autowired
	private RoleApiService roleApiService;

	@Autowired
	private PopUserScopeUtilService popUserUtilService;
	
	@Autowired
	private SendMsgUtils sendMsgUtils;
	
	@Autowired
	private LogService logService;
	
	/**
	 * 判断实体是否存在
	 * @param id
	 * @return
	 */
	@ApiOperation(value = "实体类是否存在", notes = "实体类是否存在")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id", value = "问卷ID", required = true, paramType = "query", dataType = "String") })
	@RequestMapping(value = "/entityIsExist", method = RequestMethod.POST, produces = {"application/json; charset=UTF-8" })
	public OperationResult entityIsExist(String id) {
		Questionnaire entity = this.questionnaireService.findOne(id);
		if(entity == null) return OperationResult.buildSuccessResult("notExist");
		else return OperationResult.buildSuccessResult("exist");
	}
	
	/**
	 * 获取问卷信息
	 * @param corpId
	 * @param userId
	 * @param showNumber
	 * @param request
	 * @return
	 */
	@ApiOperation(value="获取问卷信息", notes="根据用户id获取问卷信息")    
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "corpId", value = "单位ID", required = true, paramType = "query", dataType = "String"),
    	@ApiImplicitParam(name = "userId", value = "用户ID", required = true, paramType = "query", dataType = "String"),
    	@ApiImplicitParam(name = "showNumber", value = "显示条数", required = true, paramType = "query", dataType = "String"),
    })
    @RequestMapping(value="/getQuesInfoByUserId", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    public OperationResult getQuesInfoByUserId(@RequestParam("corpId") String corpId,@RequestParam("userId") String userId,@RequestParam("showNumber") String showNumber,HttpServletRequest request) {
		List<Questionnaire> list = new ArrayList<Questionnaire>();
//		if("1".equals(isAdmin)){
//			list =questionnaireService.findAll();
			list = questionnaireService.getQuesInfoByUserId(userId, corpId,TOKEN);
//		}else{
//			list = questionnaireService.getQuesInfoByUserId(userId, corpId,TOKEN);
//		}
		if(list == null || list.size()==0){
			return OperationResult.buildSuccessResult("该用户没有问卷信息");
		}else{
			int num = Integer.parseInt(showNumber);
			List<Map<String,Object>> mapList = questionnaireService.getQuesPageInfo(list, TOKEN, corpId, num);
			return OperationResult.buildSuccessResult("获取问卷信息成功",mapList);
		}
    }
	
	/**
	 * 获取问卷数量
	 * @param corpId
	 * @param userId
	 * @param isAdmin
	 * @param request
	 * @return
	 */
	@ApiOperation(value="获取问卷数量", notes="根据用户id获取问卷数量")    
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "corpId", value = "单位ID", required = true, paramType = "query", dataType = "String"),
    	@ApiImplicitParam(name = "userId", value = "用户ID", required = true, paramType = "query", dataType = "String"),
    	@ApiImplicitParam(name = "isAdmin", value = "是否是超管", required = true, paramType = "query", dataType = "String")
    })
    @RequestMapping(value="/getQuesCount", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    public OperationResult getQuesCount(@RequestParam("corpId") String corpId,@RequestParam("userId") String userId,@RequestParam("isAdmin") String isAdmin,HttpServletRequest request) {
		List<Questionnaire> list = new ArrayList<Questionnaire>();
		if("1".equals(isAdmin)){
			list = questionnaireService.getQuesInfoByUserId(userId, corpId,TOKEN);
		}else{
			list = questionnaireService.getQuesInfoByUserId(userId, corpId,TOKEN);
		}
		int count =0;
		if(list != null && list.size()>0){
			for(Questionnaire q : list){
			    if(q.getPublish()==Questionnaire.PublishEnum.PUBLISH.getCode() && q.getCloseDate().after(new Date())){
			    	count ++;
				}
			}
//			count =list.size();
		}
		Map<String,Integer> map = new HashMap<String,Integer>();
		map.put("count", count);
		return OperationResult.buildSuccessResult("获取问卷数量成功",map);
    }
	
	 @RequestMapping(value = "/questionnaireJob", method = RequestMethod.GET)
	 public OperationResult questionnaireJob() {
	      LOG.debug("questionnaireJob执行开始。。。");
	      try {
	    	  //更新问卷状态
	    	  questionnaireService.updateQuestionnaireStatus();
	    	  //更新答卷状态
	    	  answerStatusService.updateStatusToSubmitByDate();
	          Thread.sleep(5000);
	      } catch (InterruptedException e) {
	          e.printStackTrace();
	      }
	      LOG.debug("questionnaireJob执行结束。");
	      return OperationResult.buildSuccessResult("执行成功");
	  }
	 
	 /**
	     * 定时开启问卷  发送推送消息
	     * @return
	     */
	    @GetMapping("/sendmsg")
	    public OperationResult questionnaireSendMsg(HttpServletRequest request){

	        String token = JwtUtils.resolveToken(request);


	        List<Questionnaire> questionnaireList = questionnaireService.getQuesNoClose();
	        for(Questionnaire questionnaire : questionnaireList){
//	            questionnaireService.updateQuStatus(questionnaire.getId(),"1",questionnaire.getCorpId(),"",request);
	            Long starBeforeTenTime = questionnaire.getStartDate().getTime() - 600000;  //提前十分钟
	            Long nowTime = new Date().getTime();
	            int topicNum = topicService.getQuesTopic(questionnaire.getId());
	            if(questionnaire.getStatus() != Questionnaire.StatusEnum.CLOSE.getCode()
	                    && topicNum > 0 && starBeforeTenTime <= nowTime
	                    && questionnaire.getSendStatus() == Questionnaire.SendStatusEnum.NOSEND.getCode()){
	               questionnaireService.sendQuesForJob(questionnaire.getId(),questionnaire.getCorpId(),token,request);
	            }
	        }

	        return OperationResult.buildSuccessResult();
	    }
	    
	    /**
	     * 定时更新问卷状态
	     * @return
	     */
	    @RequestMapping(value = "/updateOverdue", method = RequestMethod.GET)
	    @ResponseBody
	    public OperationResult updateOverdue(HttpServletRequest request){
	    	// 更新过期问卷
	        try {
	        	questionnaireService.updateOverdueQuestionnaire();
	        }catch (Exception e){
	        	LOG.error("目标管理-问卷：更新问卷超期信息schedule运行失败", e);
	        }

	        return OperationResult.buildSuccessResult();
	    }
	    
	    /**
	     * 定时发布问卷
	     * @param request
	     * @return
	     */
	    @RequestMapping(value = "/publishQuestionnaire", method = RequestMethod.GET)
	    @ResponseBody
	    public OperationResult publishQuestionnaire(HttpServletRequest request){
	        try {
	        	List<Questionnaire> list = this.questionnaireService.getPublishQuestionnaire(new Date());
	        	if (CollectionUtils.isNotEmpty(list)) {
	        		List<String> idList = new ArrayList<>();
	        		for (Questionnaire questionnaire : list) {
	        			idList.add(questionnaire.getId());
	        		}
	        		int count = this.questionnaireService.publishQuestionnaire(idList);
	    			if(count > 0){
	    				String token = JwtUtils.createJwtToken(GlobalConstant.X_APP_AUTH);
	    				for (Questionnaire questionnaire : list) {
	    					this.questionnaireService.sendThreadQues(questionnaire.getId(),questionnaire.getCreatedBy(),GlobalConstant.CORP_ID,token,request);
	    				}
	    				return OperationResult.buildSuccessResult("定时发布问卷成功");
	    			}
	        	}
	        	return OperationResult.buildSuccessResult();
	        }catch (Exception e){
	        	LOG.error("目标管理-问卷：定时发布问卷schedule运行失败", e);
	        	return OperationResult.buildFailureResult("定时发布问卷失败");
	        }
	    }
	 
/*======================================钉钉接口==================================================*/

	 	/**
	 	 * 获取首页问卷列表
	 	 * @param quesType
	 	 * @param corpId
	 	 * @param userId
	 	 * @param quespublish
	 	 * @param startDate
	 	 * @param endDate
	 	 * @param token
	 	 * @param page
	 	 * @param pageSize
	 	 * @param search
	 	 * @param request
	 	 * @return
	 	 * @throws ParseException
	 	 */
	 	@ApiOperation(value="获取首页问卷列表", notes="获取首页问卷列表")
	    @ApiImplicitParams({
	    	@ApiImplicitParam(name = "corpId", value = "单位ID", required = true, paramType = "query", dataType = "String"),
	    	@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "String"),
	    	@ApiImplicitParam(name = "token", value = "token", required = true, paramType = "query", dataType = "String"),
	    	@ApiImplicitParam(name = "page", value = "分页页码", required = true, paramType = "query", dataType = "String"),
	    	@ApiImplicitParam(name = "pageSize", value = "页容量", required = true, paramType = "query", dataType = "String"),
	    	@ApiImplicitParam(name = "search", value = "搜索内容", required = true, paramType = "query", dataType = "String"),

			@ApiImplicitParam(name = "quesType", value = "搜索问卷类型", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "quespublish", value = "搜索问卷状态", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "startDate", value = "搜索开始问卷日期", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "endDate", value = "搜索结束问卷日期", required = true, paramType = "query", dataType = "String"),
	    })
	    @RequestMapping(value="/getQuesList", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
	    public OperationResult getQuesList(@RequestParam("quesType") String quesType,@RequestParam("corpId") String corpId,@RequestParam("userId") String userId,@RequestParam("quespublish")String quespublish,@RequestParam("startDate")String startDate,@RequestParam("endDate")String endDate
	    		,@RequestParam("token") String token,@RequestParam("page") String page,@RequestParam("pageSize") String pageSize,@RequestParam("search") String search,HttpServletRequest request) throws ParseException {
			List<Map<String, Object>> roleList = roleApiService.getRolesByUserId(userId, corpId, TOKEN);
			boolean result = false;
			if (!roleList.isEmpty()) {
				String roleCode = "";
				for (Map<String, Object> map : roleList) {
					roleCode = StringUtils.null2String(map.get("roleCode"));
					if("appAdminRole".equals(roleCode)){
						result = true;
						break;
					}
				}
			}
			String userIdStr = userId;
			//AuthUtils.isSuperAdmin(userId) ||
			if(result){
				userIdStr = "";
			}
			List<Map> map = questionnaireService.getQuesList(corpId,userIdStr,quesType,page,
					pageSize,search,quespublish,startDate,endDate);
//			Date currentDate = new Date();
//			for(Map ques : map){
//				String queType = ques.get("type").toString();
//				String startDateStr = ques.get("startDate").toString();
//				String endDateStr = ques.get("endDate").toString();
//				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//				Date startDate = sdf.parse(startDateStr);
//		    	Date endDate = sdf.parse(endDateStr);

//		    	String status = StringUtils.null2String(ques.get("status"));
//		    	String id = StringUtils.null2String(ques.get("id"));
//				int count = this.topicService.getQuesTopic(id);
//				if(startDate.getTime()<=currentDate.getTime() && endDate.getTime() > currentDate.getTime()
//						&& StringUtils.equals(Questionnaire.StatusEnum.NOOPEN.getCode(),status)){
//					if(count != 0) {
//						ques.put("status",Questionnaire.StatusEnum.OPEN.getCode());
//					}
//				}
//				if(endDate.getTime()<=currentDate.getTime() && !StringUtils.equals(Questionnaire.StatusEnum.CLOSE.getCode(),status)){
//					if(count != 0) {
//						ques.put("status",Questionnaire.StatusEnum.CLOSE.getCode());
//					}
//				}

//				ques.put("endDate", sdf.format(endDate));
//		    	ques.put("startDate", sdf.format(startDate));
//				Map<String,Object> dict=dictDetailApiService.getDictDataByCode(queType, corpId, token);
//				if("questionnaireVote".equals(queType)) {
//					ques.put("typeName", "投票");
//				}else {
//					ques.put("typeName", "调查");
//				}
//			}
			return OperationResult.buildSuccessResult("获取问卷列表成功",map);
	    }

	 	/**
	 	 * 获取我的答卷列表
	 	 * @param quesType
	 	 * @param corpId
	 	 * @param userId
	 	 * @param status
	 	 * @param startDate
	 	 * @param endDate
	 	 * @param token
	 	 * @param page
	 	 * @param pageSize
	 	 * @param search
	 	 * @param request
	 	 * @return
	 	 * @throws ParseException
	 	 */
	 	@ApiOperation(value="获取首页问卷列表", notes="获取首页问卷列表")
	    @ApiImplicitParams({
	    	@ApiImplicitParam(name = "corpId", value = "单位ID", required = true, paramType = "query", dataType = "String"),
	    	@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "String"),
	    	@ApiImplicitParam(name = "token", value = "token", required = true, paramType = "query", dataType = "String"),
	    	@ApiImplicitParam(name = "page", value = "分页页码", required = true, paramType = "query", dataType = "String"),
	    	@ApiImplicitParam(name = "pageSize", value = "页容量", required = true, paramType = "query", dataType = "String"),
	    	@ApiImplicitParam(name = "search", value = "搜索内容", required = true, paramType = "query", dataType = "String"),
				@ApiImplicitParam(name = "quesType", value = "问卷类型", required = true, paramType = "query", dataType = "String"),
				@ApiImplicitParam(name = "status", value = "答卷状态", required = true, paramType = "query", dataType = "String"),
				@ApiImplicitParam(name = "startDate", value = "问卷创建时间开始查询时间", required = true, paramType = "query", dataType = "String"),
				@ApiImplicitParam(name = "endDate", value = "问卷创建时间结束查询时间", required = true, paramType = "query", dataType = "String"),
	    })
	    @RequestMapping(value="/getAnswerList", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
	    public OperationResult getAnswerList(@RequestParam("quesType") String quesType,@RequestParam("corpId") String corpId,@RequestParam("userId") String userId,@RequestParam("status") String status,@RequestParam("startDate") String startDate,@RequestParam("endDate") String endDate,@RequestParam("token") String token,@RequestParam("page") String page,@RequestParam("pageSize") String pageSize,@RequestParam("search") String search,HttpServletRequest request) throws ParseException {
			@SuppressWarnings("rawtypes")
			List<Map> map = answerService.getAnswerList(quesType,corpId,userId,token,page,pageSize,search,status,startDate,endDate);
//			Date currentDate = new Date();
//			List<Map> result = new ArrayList<>();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			for(Map ques : map){
				String queType = ques.get("type").toString();
//				String startDateStr = ques.get("startDate").toString();
//				String endDateStr = ques.get("endDate").toString();
				String createdDateStr = ques.get("createdDate").toString();
//				Date startDate = sdf.parse(startDateStr);
//		    	Date endDate = sdf.parse(endDateStr);
		    	Date createdDate = sdf.parse(createdDateStr);

//				String status = StringUtils.null2String(ques.get("status"));
				String id = StringUtils.null2String(ques.get("id"));
//				int count = this.topicService.getQuesTopic(id);
//				if(startDate.getTime()<=currentDate.getTime() && endDate.getTime() > currentDate.getTime()
//						&& StringUtils.equals(Questionnaire.StatusEnum.NOOPEN.getCode(),status)){
//					if(count != 0) {
//						ques.put("status",Questionnaire.StatusEnum.OPEN.getCode());
//					}
//				}
//				if(endDate.getTime()<=currentDate.getTime() && !StringUtils.equals(Questionnaire.StatusEnum.CLOSE.getCode(),status)){
//					if(count != 0) {
//						ques.put("status",Questionnaire.StatusEnum.CLOSE.getCode());
//					}
//				}

//		    	ques.put("startDate", sdf.format(startDate));
//		    	ques.put("endDate", sdf.format(endDate));
		    	ques.put("createdDate", DateUtils.formatDate(createdDate));
//				Map<String,Object> dict=dictDetailApiService.getDictDataByCode(queType, corpId, token);
//				if("questionnaireVote".equals(queType)) {
//					ques.put("typeName", "投票");
//				}else {
//					ques.put("typeName", "调查");
//				}
				//答卷的状态
				String answerStatus = StringUtils.null2String(ques.get("answerStatus"));
				if(StringUtils.equals(answerStatus,QusetionnaireAnswerStatus.StatusEnum.NOANSWER.getCode()) || StringUtils.isBlank(answerStatus)){
					ques.put("answerStatus", "0");
					ques.put("status", "待答卷");
				}else if(StringUtils.equals(answerStatus,QusetionnaireAnswerStatus.StatusEnum.SUBMIT.getCode())){
					ques.put("status", "已提交");
				}else if(StringUtils.equals(answerStatus,QusetionnaireAnswerStatus.StatusEnum.DRAFT.getCode())){
					ques.put("status","草稿");
				}else if(StringUtils.equals(answerStatus,QusetionnaireAnswerStatus.StatusEnum.BACK.getCode())){
					ques.put("status","已回退");
				}else if(StringUtils.equals(answerStatus, "4")) {
					ques.put("status", "已提交");
				}
//				status = StringUtils.null2String( ques.get("status"));
//				if(StringUtils.equals("0",type) && StringUtils.equals(Questionnaire.StatusEnum.OPEN.getCode(),status)){
//					result.add(ques);
//				}
			}
//			if(StringUtils.equals("0",type)){
//				return OperationResult.buildSuccessResult("获取问卷列表成功",map);
//			}
			return OperationResult.buildSuccessResult("获取问卷列表成功",map);
	    }


	 	/**
	 	 * 获取首页问卷详情
	 	 * @param id
	 	 * @param token
	 	 * @param userId
	 	 * @param corpId
	 	 * @param isAnwser
	 	 * @param request
	 	 * @return
	 	 * @throws ParseException
	 	 */
	 	@ApiOperation(value="获取首页问卷详情", notes="获取首页问卷详情")    
	    @ApiImplicitParams({
	    	@ApiImplicitParam(name = "id", value = "业务数据ID", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "isAnwser", value = "是否显示答案状态位", required = true, paramType = "query", dataType = "String"),
	    	@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "String"),
	    	@ApiImplicitParam(name = "corpId", value = "corpid", required = true, paramType = "query", dataType = "String"),
	    	@ApiImplicitParam(name = "token", value = "token", required = true, paramType = "query", dataType = "String"),
	    })
	    @RequestMapping(value="/getQuesInfo", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
	    public OperationResult getQuesInfo(@RequestParam("id") String id,@RequestParam("token") String token,@RequestParam("userId") String userId,@RequestParam("corpId") String corpId,@RequestParam("isAnwser") String isAnwser,HttpServletRequest request) throws ParseException {
	 		Map<String, Object> map = new HashMap<>();
	 		//Map oq = questionnaireService.getQuesInfoById(id);
	 		Questionnaire oq = questionnaireService.findOne(id);
//			if(oq != null && oq.size()>0) {
//				String startDateStr = oq.get("startDate").toString();
//				String endDateStr = oq.get("endDate").toString();
//				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//		    	Date startDate = sdf.parse(startDateStr);
//		    	Date endDate = sdf.parse(endDateStr);
//		    	oq.put("startDate", DateUtils.formatDate(startDate, "MM-dd HH:mm"));
//		    	oq.put("endDate", DateUtils.formatDate(endDate, "MM-dd HH:mm"));
//			}
			if(oq == null) {
				map.put("isDeleted", true);
				return OperationResult.buildSuccessResult("获取问卷信息失败",map);
			}else {
				map.put("isDeleted", false);
			}
			List<QuestionnaireTopic> list = topicService.getDingTopicOPtionInfo(id,userId,isAnwser,TOKEN);
			map.put("topicSetting", list);
	    	String titleSetting = StringUtils.null2String(oq.getTitleSetting());
	    	String createdDate = StringUtils.null2String(oq.getCreatedDate());
//	    	if(StringUtils.isNotBlank(createdDate)){
//	    		oq.put("createdDate",createdDate.substring(0,10));
//			}
	    	if(!"".equals(titleSetting)){
	    		Map<String, Object> mapSetting = new HashMap<String, Object>();
	    		mapSetting = JsonUtils.readValue(titleSetting);
	    		map.put("titleSetting", mapSetting);
	    	}else{
	    		map.put("titleSetting", titleSetting);
	    	}
//	    	String queType = oq.get("type").toString();
//	    	if("questionnaireVote".equals(queType)) {
//				oq.put("typeName", "投票");
//			}else {
//				oq.put("typeName", "调查");
//			}
	    	map.put("entity", oq);
	    	//获取问卷状态
//			int status = this.questionnaireService.updateQuStatus(id,userId,corpId,token,request);
//			map.put("status", status);
			//获取用户答卷状态
            QusetionnaireAnswerStatus answerStatus = this.answerStatusService.findAnswerStatus(userId, id);
            String anStatus = "0";
            if(answerStatus != null){
            	anStatus = answerStatus.getStatus();
    			map.put("grade",answerStatus.getGrade());
    			map.put("ranking",answerStatus.getRanking());
			}
            map.put("answerStatus", anStatus);
            map.put("answerCount",  answerStatusService.getAnswerNumByQuesId(id));//答卷人数
			return OperationResult.buildSuccessResult("获取问卷信息成功",map);
	    }
	 	
//	 	@ApiOperation(value="获取问卷类型列表", notes="获取问卷类型列表")    
//	    @ApiImplicitParams({
//	    	@ApiImplicitParam(name = "corpId", value = "单位ID", required = true, paramType = "query", dataType = "String"),
//	    })
//	 	public OperationResult getTypeList(@RequestParam("corpId") String corpId,HttpServletRequest request){
//	 		List<Map<String,Object>> list = dictDetailApiService.getDictDetailByCode("questionnaireType",corpId,TOKEN);
//	    	map.put("types", list);
//	 	}
	 	/**
		 * 将钉钉的用户id或者部门（岗位id）转换成pc端的id
		 * @param viewerUserId
		 * @param recepuserName 
		 * @param user
		 * @return String
		 */
		public String changeId(String viewerUserId,String corpId,String token, String recepuserName){
			JSONArray platformArray = new JSONArray();
			  JSONObject object = new JSONObject();
			  List<String> l = userApiService.getUserIdBySysOrThird(viewerUserId,"0", "DING", corpId,token);
				  if (!CollectionUtils.isEmpty(l)) {
					  	String s_change = l.get(0);
					  	object.put("scopeValue", s_change);
					  	object.put("scopeType", "user");
					  	object.put("scopeName", recepuserName);
				  }
			  platformArray.add(object);
			return platformArray.size() == 0 ? "" : JSON.toJSONString(platformArray);
		}
	 	 /**
	     * 保存问卷
	     * @param entity
	     * @param model
	     * @return
	     * @throws ParseException 
	     */
	 	@ApiOperation(value="保存问卷", notes="保存问卷信息")
	    @ApiImplicitParams({
	    	@ApiImplicitParam(name = "corpId", value = "单位ID", required = true, paramType = "query", dataType = "String"),
	    	@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "String"),
	    	@ApiImplicitParam(name = "orgId", value = "组织id", required = true, paramType = "query", dataType = "String"),
	    	@ApiImplicitParam(name = "token", value = "token", required = true, paramType = "query", dataType = "String"),
	    	@ApiImplicitParam(name = "data", value = "表单内容", required = true, paramType = "query", dataType = "body"),
	    })
	    @RequestMapping(value = "/save", method = RequestMethod.POST)
	    public OperationResult save(@RequestBody Map data,@RequestParam("corpId") String corpId,@RequestParam("userId") String userId,@RequestParam("orgId") String orgId,@RequestParam("token") String token, HttpServletRequest request) throws ParseException {
//	 		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	 		String id = StringUtils.null2String(data.get("id"));
	 		String name = StringUtils.null2String(data.get("name"));
	    	boolean flag = questionnaireService.checkName(id, name, corpId);
	    	if(flag){
	    		return OperationResult.buildFailureResult("该问卷名称已存在");
	    	}
/*	    	String jsonStrQuestionnaireScope = StringUtils.null2String(request.getParameter("jsonStrQuestionnaireScope"));
	    	String jsonStrAnswerScope = StringUtils.null2String(request.getParameter("jsonStrAnswerScope"));
	    	if(!ValidateUtils.validateChar(jsonStrQuestionnaireScope, "%+")){
				throw new ValidationException("非法参数");
			}
	    	if(!ValidateUtils.validateChar(jsonStrAnswerScope, "%+")){
				throw new ValidationException("非法参数");
			}
	    	String quesScope = entity.getQuestionnaireScope();
	    	if(!"".equals(jsonStrQuestionnaireScope)){
	    		if("".equals(StringUtils.null2String(quesScope))){
	    			quesScope = UuidUtils.UUID();
	    		}
	    		this.popUserUtilService.saveScopeData("oa_questionnaire_scope", quesScope, jsonStrQuestionnaireScope, "oa_questionnaire","questionnaire_scope");
	    	}else{
	    		this.popUserUtilService.delScopeMethod("oa_questionnaire_scope",quesScope,"oa_questionnaire","questionnaire_scope");
	    	}
	    	String answerScope = entity.getAnswerScope();
	    	if(!"".equals(jsonStrAnswerScope)){
	    		if("".equals(StringUtils.null2String(answerScope))){
	    			answerScope = UuidUtils.UUID();
	    		}
	    		this.popUserUtilService.saveScopeData("oa_questionnaire_scope",answerScope , jsonStrAnswerScope, "oa_questionnaire","answer_scope");
	    	}else{
	    		this.popUserUtilService.delScopeMethod("oa_questionnaire_scope",answerScope,"oa_questionnaire","answer_scope");
	    	}*/
	    	
	    	String quesType = data.get("quesType")==null?"":data.get("quesType").toString();
	    	String description =data.get("description")==null?"": data.get("description").toString();
			Questionnaire entity = null;
			String oldName = "";
			if(StringUtils.isNotBlank(id)){
				entity = questionnaireService.findOne(id);
				oldName = entity.getName();
			}else {
				entity = new Questionnaire();
				entity.setCreatedBy(userId);
		    	entity.setCreatedOrg(orgId);
			}
			if(entity.getPublish()==Questionnaire.PublishEnum.DIES_VENIT.getCode()) {
	    		entity.setPublish(Questionnaire.PublishEnum.NOPUBLISH.getCode());
	    	}
	    	entity.setName(name);
	    	entity.setType(quesType);
	    	entity.setDescription(description);
	    	entity.setCloseDate(DateUtils.parseDate(data.get("closeDate")));
	    	
	    	/**
	    	 * 根据适用范围  获取总应答题人数
	    	 */
	    	String quesScopeList = data.get("quesScopeList").toString();
	    	if(quesScopeList == null || JSONArray.parseArray(quesScopeList).size() == 0) {
	    		List<Map> list = questionnaireService.getAllUser(corpId);
	        	entity.setAllUserNum(list.size());
	    	}else {
	    		Set<String> set = questionnaireService.getAllUserNum(quesScopeList, corpId, token); 
	        	entity.setAllUserNum(set.size());
	    	}
	    	
	    	String quesScope = entity.getQuestionnaireScope();
	    	if(quesScopeList != null && JSONArray.parseArray(quesScopeList).size() > 0){
	    		if("".equals(StringUtils.null2String(quesScope))){
	    			quesScope = UuidUtils.UUID();
	    			entity.setQuestionnaireScope(quesScope);
	    		}
	    		this.popUserUtilService.saveScopeData("oa_questionnaire_scope", quesScope, quesScopeList, "oa_questionnaire","questionnaire_scope");
	    	}else{
	    		this.popUserUtilService.delScopeMethod("oa_questionnaire_scope",quesScope,"oa_questionnaire","questionnaire_scope");
	    		entity.setQuestionnaireScope(null);
	    	}
	    	
	    	String answerScopeList = data.get("answerScopeList").toString();
	    	String answerScope = entity.getAnswerScope();
	    	if(answerScopeList != null && JSONArray.parseArray(answerScopeList).size() > 0){
	    		if("".equals(StringUtils.null2String(answerScope))){
	    			answerScope = UuidUtils.UUID();
	    			entity.setAnswerScope(answerScope);
	    		}
	    		this.popUserUtilService.saveScopeData("oa_questionnaire_scope",answerScope , answerScopeList, "oa_questionnaire","answer_scope");
	    	}else{
	    		this.popUserUtilService.delScopeMethod("oa_questionnaire_scope",answerScope,"oa_questionnaire","answer_scope");
	    		entity.setAnswerScope(null);
	    	}
	    	
//	    	String answerScopeList = data.get("answerScopeList").toString();
//
//	    	if(answerScopeList!=null &&JSONArray.parseArray(answerScopeList).size()>0) {
//	    		String answerScope = UuidUtils.UUID();
//	    		entity.setAnswerScope(answerScope);
//	    		this.popUserScopeUtilService.saveScopeData("oa_questionnaire_scope", answerScope, answerScopeList, "oa_questionnaire","answer_scope");
//	    	}else {
//	    		
//	    	}
//	    	String quesScopeList = data.get("quesScopeList").toString();
//	    	if(quesScopeList!=null &&JSONArray.parseArray(quesScopeList).size()>0) {
//	    		String quesScope = UuidUtils.UUID();
//	    		entity.setQuestionnaireScope(quesScope);
//	    		this.popUserScopeUtilService.saveScopeData("oa_questionnaire_scope", quesScope, quesScopeList, "oa_questionnaire","questionnaire_scope");
//	    	}
//	    	Date date = new Date();
//	    	entity.setCreatedDate(date);
//	    	String startDateStr = data.get("startDate")==null?"":data.get("startDate").toString();
//	    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//	    	Date startDate = sdf.parse(startDateStr);
//	    	String endDateStr = data.get("endDate")==null?"":data.get("endDate").toString();
//	    	Date endDate = sdf.parse(endDateStr);
//	    	if(startDate.getTime()> date.getTime()){
//	    		//开始时间大于当前日期问卷未开启
//	    		entity.setStatus("2");
//	    	}
//
//	    	if(startDate.getTime()<= date.getTime()){
//	    		//开始时间大于当前日期问卷开启
//	    		entity.setStatus("1");
//	    	}
//	    	if(endDate.getTime()<= date.getTime()){
//	    		//结束时间小于当前时间问卷关闭
//	    		entity.setStatus("0");
//	    	}
//	    	entity.setStartDate(startDate);
//	    	entity.setEndDate(endDate);
	    	entity.setCorpId(corpId);
	    	if(StringUtils.isBlank(id)){
				entity.setPublish(Questionnaire.PublishEnum.NOPUBLISH.getCode());
			}
	    	questionnaireService.save(entity);
	    	if(StringUtils.isNotBlank(id)){
	    		// 日志启用标记
		    	boolean optLogFlag = this.logService.checkOptLog(corpId, "questionnaireLog:manage:02", TOKEN);
		    	if (optLogFlag) {
		    		//记录日志
			  		this.logService.saveModuleLog("questionnaireLog:manage:02", oldName, "");
		    	}
			}

	    	//保存题目选项
//	    	List<QuestionnaireTopic> listTopic = new ArrayList<QuestionnaireTopic>();
//	    	List<QuestionnaireTopicOptions> listOptions = new ArrayList<QuestionnaireTopicOptions>();
//	    	String quesitionnaireId = entity.getId();
//	    	List list = (List) data.get("list");//单选
	    	/*
	    	List sinselect = (List) data.get("sinselect");//单选
	    	List multiselect =  (List) data.get("multiselect");//多选
	    	List check = (List) data.get("check"); //下拉
	    	List fillInBlanks = (List) data.get("fillInBlanks");//填空
	    	List answer = (List) data.get("answer"); //问答
	    	List field =(List) data.get("field"); //附件
	    	List scale = (List) data.get("scale"); //量表
	    	List mulscale = (List) data.get("mulscale"); //矩阵量表
	    	List illustrate = (List) data.get("illustrate"); //说明
	    	List paging = (List) data.get("paging"); //分页
	    	*/
//	    	if(list != null && list.size()>0){
//	    		for(int i=0;i<list.size();i++){
//	    			Map<String,Object> topicMap = (Map<String, Object>) list.get(i);
//	    			int topicOrderNo = i+1;
//
//	    			//String topicAllSetting = request.getParameter(topicOrderNo+"sinselect");
//	    			List optionSetting = (List) topicMap.get("options");
//	    			//Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
//	    			topicMap.put("sortNo",topicOrderNo);
//	    			QuestionnaireTopic topic = new QuestionnaireTopic();
//	    			topic = topicService.getDingSaveTopicInfo(topicMap, quesitionnaireId, (String) topicMap.get("quesType"));
//	    			topic.setCreatedBy(userId);
//	    			topic.setCreatedOrg(orgId);
//	    			topic.setCreatedDate(date);
//	    			listTopic.add(topic);
//
//	    			List<QuestionnaireTopicOptions> listOption = optionService.getDingSaveOptionsInfo(optionSetting, topic.getId(),userId,orgId);
//	    			listOptions.addAll(listOption);
//	    		}
//	    	}
	    	/*if(multiselect !=null && multiselect.size()>0){
	    		for(int i=0;i<multiselect.size();i++){
	    			String topicOrderNo = (String) multiselect.get(i);
	    			String topicAllSetting = request.getParameter(topicOrderNo+"multiselect");
	    			String optionSetting =request.getParameter(topicOrderNo+"option");
	    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
	    			QuestionnaireTopic topic = new QuestionnaireTopic();
	    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "multiselect");
	    			listTopic.add(topic);
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
	    		}
	    	}
	    	if(check != null && check.size()>0){
	    		for(int i=0;i<check.size();i++){
	    			String topicOrderNo = (String) check.get(i);
	    			String topicAllSetting = request.getParameter(topicOrderNo+"check");
	    			String optionSetting =request.getParameter(topicOrderNo+"option");
	    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
	    			QuestionnaireTopic topic = new QuestionnaireTopic();
	    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "check");
	    			listTopic.add(topic);
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
	    		}
	    	}
	    	if(fillInBlanks !=null && fillInBlanks.size()>0){
	    		for(int i=0;i<fillInBlanks.size();i++){
	    			String topicOrderNo = (String) fillInBlanks.get(i);
	    			String topicAllSetting = request.getParameter(topicOrderNo+"fillInBlanks");
	    			String optionSetting =request.getParameter(topicOrderNo+"option");
	    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
	    			QuestionnaireTopic topic = new QuestionnaireTopic();
	    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "fillInBlanks");
	    			listTopic.add(topic);
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
	    		}
	    	}
	    	if(answer !=null && answer.size()>0){
	    		for(int i=0;i<answer.size();i++){
	    			String topicOrderNo = (String) answer.get(i);
	    			String topicAllSetting = request.getParameter(topicOrderNo+"answer");
	    			String optionSetting =request.getParameter(topicOrderNo+"option");
	    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
	    			QuestionnaireTopic topic = new QuestionnaireTopic();
	    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "answer");
	    			listTopic.add(topic);
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
	    		}
	    	}
	    	if(field !=null && field.size()>0){
	    		for(int i=0;i<field.size();i++){
	    			String topicOrderNo = (String) field.get(i);
	    			String topicAllSetting = request.getParameter(topicOrderNo+"field");
	    			String optionSetting =request.getParameter(topicOrderNo+"option");
	    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
	    			QuestionnaireTopic topic = new QuestionnaireTopic();
	    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "field");
	    			listTopic.add(topic);
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
	    		}
	    	}
	    	if(scale !=null && scale.size()>0){
	    		for(int i=0;i<scale.size();i++){
	    			String topicOrderNo = (String) scale.get(i);
	    			String topicAllSetting = request.getParameter(topicOrderNo+"scale");
	    			String optionSetting =request.getParameter(topicOrderNo+"option");
	    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
	    			QuestionnaireTopic topic = new QuestionnaireTopic();
	    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "scale");
	    			listTopic.add(topic);
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
	    		}
	    	}
	    	if(mulscale != null && mulscale.size()>0){
	    		for(int i=0;i<mulscale.size();i++){
	    			String topicOrderNo = (String) mulscale.get(i);
	    			String topicAllSetting = request.getParameter(topicOrderNo+"mulscale");
	    			String optionSetting =request.getParameter(topicOrderNo+"option");
	    			String optionChildSetting  =request.getParameter(topicOrderNo+"childoption");
	    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
	    			QuestionnaireTopic topic = new QuestionnaireTopic();
	    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "mulscale");
	    			listTopic.add(topic);
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting,optionChildSetting, topic.getId());
	    			listOptions.addAll(listOption);
	    		}
	    	}
	    	if(illustrate !=null && illustrate.size()>0){
	    		for(int i=0;i<illustrate.size();i++){
	    			String topicOrderNo = (String) illustrate.get(i);
	    			String topicAllSetting = request.getParameter(topicOrderNo+"illustrate");
	    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
	    			QuestionnaireTopic topic = new QuestionnaireTopic();
	    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "illustrate");
	    			listTopic.add(topic);
	    		}
	    	}
	    	if(paging !=null && paging.size()>0){
	    		for(int i=0;i<paging.size();i++){
	    			String topicOrderNo = (String) paging.get(i);
	    			String topicAllSetting = request.getParameter(topicOrderNo+"paging");
	    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
	    			QuestionnaireTopic topic = new QuestionnaireTopic();
	    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "paging");
	    			listTopic.add(topic);
	    		}
	    	}*/
//	    	List<String> topicList = topicService.getTopicIdByQeusId(quesitionnaireId);
//	    	if(topicList != null && topicList.size()>0){
//	    		optionService.deleteOptionsByTopicId(topicList);
//	    		topicService.deleteTopicByQuesId(quesitionnaireId);
//	    	}
//	    	topicService.save(listTopic);
//	    	optionService.save(listOptions);
	    	return OperationResult.buildSuccessResult("保存成功");
	    }
	 	
	 	
	 	/**
	     * 保存答卷
	     * @param entity
	     * @param model
	     * @return
	     */
	 	@ApiOperation(value="保存答卷", notes="保存答卷")    
	    @ApiImplicitParams({
	    	@ApiImplicitParam(name = "corpId", value = "单位ID", required = true, paramType = "query", dataType = "String"),
	    	@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "String"),
	    	@ApiImplicitParam(name = "orgId", value = "组织id", required = true, paramType = "query", dataType = "String"),
	    	@ApiImplicitParam(name = "quesId", value = "问卷id", required = true, paramType = "query", dataType = "String"),
	    	@ApiImplicitParam(name = "quesType", value = "问卷类型", required = true, paramType = "query", dataType = "String"),
	    	@ApiImplicitParam(name = "grade", value = "问卷得分", required = true, paramType = "query", dataType = "String"),
	    	@ApiImplicitParam(name = "timingFlag", value = "自动保存标记", required = false, paramType = "query", dataType = "String"),
	    	@ApiImplicitParam(name = "data", value = "表单内容", required = true, paramType = "query", dataType = "body"),
	    })
	    @RequestMapping(value = "/answerEdit", method = RequestMethod.POST)
	    @ResponseBody
	    public OperationResult answerEdit(@RequestBody List<Map<String,Object>> data,
	    		@RequestParam("corpId") String corpId,@RequestParam("userId") String userId,
	    		@RequestParam("orgId") String orgId,@RequestParam("quesId") String quesitionnaireId,
	    		@RequestParam("type") String submitType,@RequestParam("quesType") String quesType,
	    		@RequestParam("grade") String grade,@RequestParam("timingFlag") String timingFlag,
	    		HttpServletRequest request) {

	 		//获取用户单位id
			String token = request.getParameter("token");
			String orgIds = "";
			List<Map<String,Object>> userMapList = userApiService.getUserRelatedInfo(userId,"1",corpId,token);
			if(CollectionUtils.isNotEmpty(userMapList)){
				for(Map<String,Object> map : userMapList){
					orgIds = StringUtils.null2String(map.get("orgId"));
				}
			}
	    	//String id = data.get("id")==null?"":data.get("id").toString();
//	    	String[] sinselect = request.getParameterValues("sinselect");
//	    	String[] multiselect = request.getParameterValues("multiselect");
//	    	String[] check = request.getParameterValues("check");
//	    	String[] fillInBlanks = request.getParameterValues("fillInBlanks");
//	    	String[] answer = request.getParameterValues("answer");
//	    	String[] field = request.getParameterValues("field");
//	    	String[] scale = request.getParameterValues("scale");
//	    	String[] mulscale = request.getParameterValues("mulscale");
	    	if(data.size()==0){
	    		return OperationResult.buildFailureResult("参数不能为空");
	    	}
	    	QusetionnaireAnswerStatus aStatus = answerStatusService.findAnswerStatus(userId,quesitionnaireId);
	    	if(aStatus!=null&&"1".equals(aStatus.getStatus())) {
	    		return OperationResult.buildFailureResult("该问卷已提交");
	    	}
	    	List<QuestionnaireAnswer> list = new ArrayList<QuestionnaireAnswer>();
	    	for(int i=0;i<data.size();i++){
	    		Map<String,Object> item = data.get(i);
	    		String type = item.get("topicType").toString();
	    		if("illustrate".equals(type)) {//说明直接跳过
	    			continue;
	    		}
	    		if("sinselect".equals(type) || "trueOrFalse".equals(type)){ //单选
	    			QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
	    			oaAnswer.setAnswer(item.get("answer").toString());
	    			oaAnswer.setTopicId(item.get("id").toString());
	    			oaAnswer.setQuestionnaireId(quesitionnaireId);
	    			oaAnswer.setOptionId(item.get("answer").toString());
	    			oaAnswer.setUserId(userId);
	    			oaAnswer.setCreatedBy(userId);
	    			oaAnswer.setCreatedOrg(orgId);
	    			oaAnswer.setAnswerExt(item.get("answerExt").toString());
	    			String franction = item.get("fraction").toString();
	    			if(!"".equals(StringUtils.null2String(franction))){
	    				oaAnswer.setFraction(Float.parseFloat(franction));
	    			}
	    			list.add(oaAnswer);
	    		}else if("multiselect".equals(type)){ //多选
	    			String answer = item.get("answer").toString();
	    			String franction = item.get("fraction").toString();
	    			if(!"".equals(StringUtils.null2String(answer))){
	    				String[] answerArray = answer.split(",");
//	    				String[] franctionArray = franction.split(",");
	    				for(int j=0;j<answerArray.length;j++){
	    					QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
			    			oaAnswer.setAnswer(answerArray[j]);
			    			oaAnswer.setTopicId(item.get("id").toString());
			    			oaAnswer.setQuestionnaireId(quesitionnaireId);
			    			oaAnswer.setOptionId(answerArray[j]);
			    			oaAnswer.setUserId(userId);
			    			oaAnswer.setCreatedBy(userId);
			    			oaAnswer.setCreatedOrg(orgId);
			    			String optionlist = item.get("list").toString();
//			    			optionlist = optionlist.replace("=", ":");
			    			JSONArray optionObj = JSONArray.parseArray(optionlist);
			    			if(!optionObj.isEmpty()) {
			    				int num = 0;
			    				for(int k = 0;k<optionObj.size();k++) {
			    					
			    					JSONObject obj = JSONObject.parseObject(optionObj.get(k).toString());
				    				if("true".equals(obj.getString("checked"))) {
				    					if(num==j) {
				    						oaAnswer.setAnswerExt(obj.getString("answerExt"));
				    					}
				    					num +=1;
				    				}
			    				}
			    			}
			    			String franctionItem = franction;
			    			if(!"".equals(StringUtils.null2String(franctionItem))){
			    				oaAnswer.setFraction(Float.parseFloat(franctionItem));
			    			}
			    			list.add(oaAnswer);
	    				}
	    			}
	    		}else if("check".equals(type)){ //下拉
	    			QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
	    			oaAnswer.setAnswer(item.get("answer").toString());
	    			oaAnswer.setTopicId(item.get("id").toString());
	    			oaAnswer.setQuestionnaireId(quesitionnaireId);
	    			oaAnswer.setOptionId(item.get("answer").toString());
	    			oaAnswer.setUserId(userId);
	    			oaAnswer.setCreatedBy(userId);
	    			oaAnswer.setCreatedOrg(orgId);
	    			oaAnswer.setAnswerExt(item.get("answerExt").toString());
//	    			String franction = item.get("fraction").toString();
//	    			if(!"".equals(StringUtils.null2String(franction))){
//	    				oaAnswer.setFraction(Float.parseFloat(franction));
//	    			}
	    			list.add(oaAnswer);
	    		}else if("fillInBlanks".equals(type)){ //填空
					List<Map<String,Object>> answer = (List<Map<String,Object>>) item.get("answer");
//	    			String franction = item.get("franction").toString();
	    			if(answer.size()>0){
	    				for(int j=0;j<answer.size();j++){
	    					String answerValue = answer.get(j).get("value").toString();
//	    					if(!"".equals(answerValue)){
	    						QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
				    			oaAnswer.setAnswer(answerValue);
				    			oaAnswer.setTopicId(item.get("id").toString());
				    			oaAnswer.setQuestionnaireId(quesitionnaireId);
				    			oaAnswer.setOptionId(answer.get(j).get("id").toString());
				    			oaAnswer.setUserId(userId);
				    			oaAnswer.setCreatedBy(userId);
				    			oaAnswer.setCreatedOrg(orgId);
				    			oaAnswer.setAnswerExt("");
				    			String franctionItem = answer.get(j).get("fraction").toString();
				    			if(!"".equals(StringUtils.null2String(franctionItem))){
				    				oaAnswer.setFraction(Float.parseFloat(franctionItem));
				    			}
				    			list.add(oaAnswer);
//	    					}
	    				}
	    			}
	    		}else if("answer".equals(type) || "shortAnswer".equals(type)){ //问答
	    			QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
//	    			if(!"".equals(item.get("answer").toString())&&item.get("answer")!=null) {
	    				oaAnswer.setAnswer(item.get("answer").toString());
		    			oaAnswer.setTopicId(item.get("id").toString());
		    			oaAnswer.setQuestionnaireId(quesitionnaireId);
		    			oaAnswer.setOptionId(item.get("optionId").toString());
		    			oaAnswer.setUserId(userId);
		    			oaAnswer.setCreatedBy(userId);
		    			oaAnswer.setCreatedOrg(orgId);
		    			oaAnswer.setAnswerExt(item.get("answerExt").toString());
		    			String franction = item.get("fraction").toString();
		    			if(!"".equals(StringUtils.null2String(franction))){
		    				oaAnswer.setFraction(Float.parseFloat(franction));
		    			}
		    			list.add(oaAnswer);
//	    			}
	    			
	    		}else if("field".equals(type)){ //附件
//	    			if(!StringUtils.isEmpty(item.get("answerIds").toString())) {
	    				QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
	    				oaAnswer.setAnswer(item.get("answerIds").toString());
	    				oaAnswer.setTopicId((String)item.get("topicId"));
	    				oaAnswer.setQuestionnaireId(quesitionnaireId);
	    				if(StringUtils.isEmpty((String)item.get("optionId"))) {
	    					String uuid = UuidUtils.UUID();
	    					oaAnswer.setOptionId(uuid);
	    				}else {
	    					oaAnswer.setOptionId((String)item.get("optionId"));
	    				}
	    				oaAnswer.setCreatedBy(userId);
		    			oaAnswer.setCreatedOrg(orgId);
	    				oaAnswer.setUserId(userId);
	    				list.add(oaAnswer);
//	    			}
	    			/*oaAnswer.setAnswer(item.get("answer").toString());
	    			for(int i=0;i<field.length;i++){
	        			String topicId = field[i];
	        			String topicAllSetting = request.getParameter("field"+topicId);
	        			Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
	        			QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
	        			oaAnswer.setAnswer((String)map.get("answer"));
	        			oaAnswer.setTopicId(topicId);
	        			oaAnswer.setQuestionnaireId(quesitionnaireId);
	        			oaAnswer.setOptionId((String)map.get("optionId"));
	        			oaAnswer.setUserId(userId);
	        			list.add(oaAnswer);
	        		} */
	    		}else if("scale".equals(type)){ //矩阵
	    			QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
	    			oaAnswer.setAnswer(item.get("answer").toString());
	    			oaAnswer.setTopicId(item.get("id").toString());
	    			oaAnswer.setQuestionnaireId(quesitionnaireId);
	    			oaAnswer.setOptionId(item.get("answer").toString());
	    			oaAnswer.setUserId(userId);
	    			oaAnswer.setCreatedBy(userId);
	    			oaAnswer.setCreatedOrg(orgId);
	    			oaAnswer.setAnswerExt(item.get("answerExt").toString());
//	    			String franction = item.get("fraction").toString();
//	    			if(!"".equals(StringUtils.null2String(franction))){
//	    				oaAnswer.setFraction(Float.parseFloat(franction));
//	    			}
	    			list.add(oaAnswer);
	    		}else if("mulscale".equals(type)){ //矩阵量表
	    			List<Map<String,Object>> answer = (List<Map<String,Object>>) item.get("answer");
//	    			String franction = item.get("franction").toString();
	    			if(answer.size()>0){
	    				for(int j=0;j<answer.size();j++){
	    					if(!"".equals(answer.get(j).get("value").toString())&&answer.get(j).get("value")!=null) {
	    						String answerValue = answer.get(j).get("value").toString();
		    					if(!"".equals(answerValue)){
		    						QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
					    			oaAnswer.setAnswer(answerValue);
					    			oaAnswer.setTopicId(item.get("id").toString());
					    			oaAnswer.setQuestionnaireId(quesitionnaireId);
					    			oaAnswer.setOptionId(answer.get(j).get("id").toString());
					    			oaAnswer.setUserId(userId);
					    			oaAnswer.setCreatedBy(userId);
					    			oaAnswer.setCreatedOrg(orgId);
					    			oaAnswer.setAnswerExt("");
//					    			String franctionItem = answer.get(j).get("fraction").toString();
//					    			if(!"".equals(StringUtils.null2String(franctionItem))){
//					    				oaAnswer.setFraction(Float.parseFloat(franctionItem));
//					    			}
					    			list.add(oaAnswer);
		    					}
	    					}
	    					
	    				}
	    			}
	    		}
	    	}
	    	answerService.deleteAnswerByQuesId(userId, quesitionnaireId);
	    	answerService.save(list);
	    	//答卷状态 1是提交，2是草稿，4评卷
	    	String anStatus = submitType;
	    	// 自动保存不更新答卷状态
	    	if (!"1".equals(timingFlag)) {
		    	QusetionnaireAnswerStatus answerStatus = answerStatusService.findAnswerStatus(userId,quesitionnaireId);
		    	Date date = new Date();
		    	if(answerStatus ==null){
		    		QusetionnaireAnswerStatus newAnswerStatus = new QusetionnaireAnswerStatus();
		    		newAnswerStatus.setQuestionnaireId(quesitionnaireId);
					newAnswerStatus.setOrgId(orgIds);
		    		newAnswerStatus.setStatus(anStatus);
		    		newAnswerStatus.setCreatedBy(userId);
		    		newAnswerStatus.setCreatedOrg(orgId);
		    		if(StringUtils.isNotEmpty(grade)) newAnswerStatus.setGrade(Float.parseFloat(grade));
		    		answerStatusService.save(newAnswerStatus);
		    	}else{
		    		answerStatus.setStatus(anStatus);
//					String status = answerStatus.getStatus();
//					if(!StringUtils.equals(status,QusetionnaireAnswerStatus.StatusEnum.BACK.getCode())){
//						answerStatus.setStatus(anStatus);
//					}
//					if(StringUtils.equals(anStatus,QusetionnaireAnswerStatus.StatusEnum.SUBMIT.getCode())){
//						answerStatus.setStatus(anStatus);
//					}
					answerStatus.setOrgId(orgIds);
		    		answerStatus.setCreatedDate(date);
		    		answerStatus.setCreatedBy(userId);
		    		answerStatus.setCreatedOrg(orgId);
		    		if(StringUtils.isNotEmpty(grade)) answerStatus.setGrade(Float.parseFloat(grade));
		    		answerStatusService.save(answerStatus);
		    	}
	    	}
			if("questionnaireExam".equals(quesType) && "1".equals(anStatus)) 
				answerStatusService.rankingByGrade(quesitionnaireId);//无主观题直接进行排名
	    	if("1".equals(anStatus) || "4".equals(anStatus)) {
	    		RestClient restClient = new RestClient(true);
	    	    Map<String, String> paramMap = new HashMap<String, String>();
	    	    paramMap.put("receiver", "[{\"10\":\"" + userId + "\"}]");
	    	    paramMap.put("corpId", corpId);
	    	    paramMap.put("moduleCode", "questionnaire");
	    	    paramMap.put("dataId", quesitionnaireId);
	    	    paramMap.put("msgType", "1");
	    	    String jsonStr = restClient.post("/system/umc/message/takeMsgDone", token, paramMap);
	    	    Map<String, Object> result = JsonUtils.readValue(jsonStr);
	    	    if(MapUtils.isNotEmpty(result)) {
	    	      if("failure".equals(result.get("type"))) return OperationResult.buildFailureResult(String.valueOf(result.get("message")));
	    	    }
	    	}
	    	return OperationResult.buildSuccessResult("数据保存成功");
	    }


	    /**
	     * create by: gly<br>
	     * description:改变问卷状态<br>
	     * create time: 2019/1/9 15:05<br>
	     * @params:
	     */
		@ApiOperation(value="改变问卷状态", notes="改变问卷状态")
		@ApiImplicitParams({
				@ApiImplicitParam(name = "corpId", value = "单位ID", required = true, paramType = "query", dataType = "String"),
				@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "String"),
				@ApiImplicitParam(name = "token", value = "TOKEN", required = true, paramType = "query", dataType = "String"),
				@ApiImplicitParam(name = "quesId", value = "问卷id", required = true, paramType = "query", dataType = "String"),
				@ApiImplicitParam(name = "publish", value = "问卷状态", required = true, paramType = "query", dataType = "body"),
		})
		@GetMapping("/updateQuesPublish")
		@ResponseBody
	    public OperationResult updateQuesPublish(@RequestParam("corpId") String corpId,@RequestParam("userId") String userId,@RequestParam("token") String token,@RequestParam("quesId") String id,@RequestParam("publish") String publish,HttpServletRequest request){
			List<QuestionnaireTopic> list = topicService.getTopicOPtionInfo(id,userId,token,false);
			int length = list.size();
			if(length==0) {
				return OperationResult.buildFailureResult("未添加题目的问卷不能发布");
			}
			Questionnaire questionnaire = questionnaireService.findOne(id);
			//发布
			if(StringUtils.equals(publish,StringUtils.null2String(Questionnaire.PublishEnum.NOPUBLISH.getCode()))){
				int i = questionnaireService.updateQuesPublish(id,Questionnaire.PublishEnum.PUBLISH.getCode());
				if(i > 0){
					questionnaireService.sendThreadQues(id,userId,corpId,token,request);
//					questionnaireService.setQuesSendY(id);
				}
				return OperationResult.buildSuccessResult("发布成功");
			}
			//取消发布
			if(StringUtils.equals(publish,StringUtils.null2String(Questionnaire.PublishEnum.PUBLISH.getCode()))){
				int i = questionnaireService.updateQuesPublish(id,Questionnaire.PublishEnum.NOPUBLISH.getCode());
				if(i > 0){
					return OperationResult.buildSuccessResult("操作成功");
				}
				return OperationResult.buildSuccessResult("取消出错了");
			}
			return OperationResult.buildFailureResult("参数报错了");
		}


	/**
	 * 删除指定问卷id的问卷
	 * @param corpId
	 * @param userId
	 * @param token
	 * @param id
	 * @param request
	 * @return
	 */
	@ApiOperation(value="删除问卷", notes="删除问卷")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "corpId", value = "单位ID", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "token", value = "TOKEN", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "quesId", value = "问卷id", required = true, paramType = "query", dataType = "String"),
	})
	@GetMapping("/deletQuesById")
	@ResponseBody
	public OperationResult deletQuesById(@RequestParam("corpId") String corpId,@RequestParam("userId") String userId,@RequestParam("token") String token,@RequestParam("quesId") String id,HttpServletRequest request){
		try {
			Questionnaire questionnaire = questionnaireService.findOne(id);
			if(questionnaire == null){
				return OperationResult.buildFailureResult("该问卷不存在");
			}
			if(questionnaire.getPublish() == Questionnaire.PublishEnum.PUBLISH.getCode()){
				return OperationResult.buildFailureResult("该问卷已发布，不能删除");
			}
//			List<QuestionnaireAnswer> answerList = answerService.getAnswerByQuesId(id);
//			if(CollectionUtils.isNotEmpty(answerList)){
//				return OperationResult.buildFailureResult("该问卷已经有人答卷，不能删除");
//			}
			// 日志启用标记
	    	boolean optLogFlag = this.logService.checkOptLog(corpId, "questionnaireLog:manage:04", TOKEN);
	    	if (optLogFlag) {
	    		//记录日志
				this.logService.saveModuleLog("questionnaireLog:manage:04", questionnaire.getName(), "");
	    	}
			//查询问卷题目
			List<String> topicList = topicService.getTopicIdByQeusId(id);
			//删除答卷
			if(CollectionUtils.isNotEmpty(topicList)){
				answerStatusService.deleteStatusByQuesId(id);
				answerService.deleteAnswerByQuesId(id);
				//删除问卷选项
				optionService.deleteOptionsByTopicId(topicList);
				topicService.deleteTopicByQuesId(id);
			}
			//删除适用范围
			List<String> quesIds = new ArrayList<>();
			quesIds.add(id);
			List<String> quesScopeList = questionnaireService.getQuesScopeById(quesIds);
			List<String> answerScopeList = questionnaireService.getAnswerScopeById(quesIds);
			popUserUtilService.delScopeMethod("oa_questionnaire_scope", quesScopeList, "oa_questionnaire", "questionnaire_scope");
			popUserUtilService.delScopeMethod("oa_questionnaire_scope", answerScopeList, "oa_questionnaire", "answer_scope");
			questionnaireService.delete(questionnaire);
			sendMsgUtils.deleteMessage(Arrays.asList(id), corpId, TOKEN);
			return OperationResult.buildSuccessResult("删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			return OperationResult.buildFailureResult("删除失败");
		}
	}
	
	@ApiOperation(value="发送消息", notes="发送消息")
	@ApiImplicitParams({})
	@PostMapping("/telSendMessage")
	@ResponseBody
	public OperationResult telSendMessage(@RequestBody String paramString, HttpServletRequest request){
		Map<String, Object> paramResultMap = JsonUtils.readValue(paramString);
		String quesId = StringUtils.null2String(paramResultMap.get("quesId"));
		String userId = StringUtils.null2String(paramResultMap.get("userId"));
		String corpId = StringUtils.null2String(paramResultMap.get("corpId"));
		String token = StringUtils.null2String(paramResultMap.get("token"));
		String currentUserId = StringUtils.null2String(paramResultMap.get("currentUserId"));
		//回退问卷推送
		Map<String,Object> map = new HashMap<>();
		Questionnaire questionnaire = questionnaireService.findOne(quesId);
		//问卷名称
		map.put("quesName",questionnaire.getName());
		//问卷结束时间
		map.put("closeDate",questionnaire.getCloseDate());
		map.put("quesId", quesId);
		map.put("userIds",userId);
		map.put("type", SendMsgUtils.OVER_DUE);
		sendMsgUtils.sendMsgToApp(corpId,token,map,request,currentUserId);

		String joinIds = "[{\"10\":\"" + userId + "\"}]";
		Map<String,String> paramMap = new HashMap<>();
		paramMap.put("userId",currentUserId);
		paramMap.put("corpId",corpId);
		paramMap.put("token", token);
		paramMap.put("msgTitle","您有一份问卷截止日期快到了，请及时答卷");
		paramMap.put("dataId", UuidUtils.UUID());
		paramMap.put("msgContent","您有一份问卷截止日期快到了，请及时答卷");
		paramMap.put("url",SendMsgUtils.QUES_ANSWER_URL);
		paramMap.put("quesitionnaireId", quesId);
		paramMap.put("msgReceiver", joinIds);
		sendMsgUtils.sendMsgToOffice(paramMap);
		return OperationResult.buildSuccessResult("发送成功");
	}

	/**
	 * 查询问卷信息
	 * @param corpId
	 * @param userId
	 * @param token
	 * @param id
	 * @param type
	 * @param request
	 * @return
	 */
	@ApiOperation(value="查询问卷信息", notes="查询问卷信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "corpId", value = "单位ID", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "token", value = "TOKEN", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "quesId", value = "问卷id", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "type", value = "访问类型", required = true, paramType = "query", dataType = "String"),
	})
	@GetMapping("/getQuesInfoById")
	@ResponseBody
	public OperationResult getQuesInfoById(@RequestParam("corpId") String corpId,@RequestParam("userId") String userId,@RequestParam("token") String token,@RequestParam("quesId") String id,@RequestParam("type") String type,HttpServletRequest request){
		try {
//			Questionnaire questionnaire = questionnaireService.findOne(id);
			Map<String,Object> questionnaire = questionnaireService.getQuesById(id);
			if(MapUtils.isNotEmpty(questionnaire)){
				if("view".equals(type)) {
					// 日志启用标记
			    	boolean optLogFlag = this.logService.checkOptLog(corpId, "questionnaireLog:manage:03", TOKEN);
					if (optLogFlag) {
						//记录日志
				        this.logService.saveModuleLog("questionnaireLog:manage:03", (String)questionnaire.get("name"), "");
					}
				}
				/*
				 * 获取问卷题目的集合
				 */
				List<QuestionnaireTopic> questionnaireTopicList = topicService.getTopicOPtionInfo(id,userId,token,true);
				/*
				 * 当问卷设计过题目后，就不能在编辑问卷类型
				 */
				if(questionnaireTopicList == null || questionnaireTopicList.size() == 0) {
					questionnaire.put("typeAble","0");  //false
				}else {
					questionnaire.put("typeAble","1");   //true
				}
				return OperationResult.buildSuccessResult(questionnaire);
			}else{
				return OperationResult.buildFailureResult("问卷不存在");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return OperationResult.buildFailureResult("查询出错");
		}
	}


	/**
	 * 保存问卷
	 * @param entity
	 * @param model
	 * @return
	 * @throws ParseException
	 */
	@ApiOperation(value="保存问卷", notes="保存问卷信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "corpId", value = "单位ID", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "orgId", value = "组织id", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "token", value = "token", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "data", value = "表单内容", required = true, paramType = "query", dataType = "body"),
			@ApiImplicitParam(name = "quesId", value = "问卷id", required = true, paramType = "query", dataType = "body"),
			@ApiImplicitParam(name = "entity", value = "问卷题目", required = true, paramType = "query", dataType = "body"),
	})
	@RequestMapping(value = "/saveDesign", method = RequestMethod.POST)
	public OperationResult saveDesign(@RequestBody Map data,@RequestParam("corpId") String corpId,@RequestParam("userId") String userId,@RequestParam("orgId") String orgId,@RequestParam("quesId") String quesId,@RequestParam("entity") String entity,@RequestParam("token") String token, HttpServletRequest request) throws ParseException {

//		String id = data.get("id")==null?"":data.get("id").toString();
//		String name = data.get("name")==null?"":data.get("name").toString();
//		boolean flag = questionnaireService.checkName(id, name, corpId);
//		if(flag){
//			return OperationResult.buildFailureResult("该问卷名称已存在");
//		}
/*	    	String jsonStrQuestionnaireScope = StringUtils.null2String(request.getParameter("jsonStrQuestionnaireScope"));
	    	String jsonStrAnswerScope = StringUtils.null2String(request.getParameter("jsonStrAnswerScope"));
	    	if(!ValidateUtils.validateChar(jsonStrQuestionnaireScope, "%+")){
				throw new ValidationException("非法参数");
			}
	    	if(!ValidateUtils.validateChar(jsonStrAnswerScope, "%+")){
				throw new ValidationException("非法参数");
			}
	    	String quesScope = entity.getQuestionnaireScope();
	    	if(!"".equals(jsonStrQuestionnaireScope)){
	    		if("".equals(StringUtils.null2String(quesScope))){
	    			quesScope = UuidUtils.UUID();
	    		}
	    		this.popUserUtilService.saveScopeData("oa_questionnaire_scope", quesScope, jsonStrQuestionnaireScope, "oa_questionnaire","questionnaire_scope");
	    	}else{
	    		this.popUserUtilService.delScopeMethod("oa_questionnaire_scope",quesScope,"oa_questionnaire","questionnaire_scope");
	    	}
	    	String answerScope = entity.getAnswerScope();
	    	if(!"".equals(jsonStrAnswerScope)){
	    		if("".equals(StringUtils.null2String(answerScope))){
	    			answerScope = UuidUtils.UUID();
	    		}
	    		this.popUserUtilService.saveScopeData("oa_questionnaire_scope",answerScope , jsonStrAnswerScope, "oa_questionnaire","answer_scope");
	    	}else{
	    		this.popUserUtilService.delScopeMethod("oa_questionnaire_scope",answerScope,"oa_questionnaire","answer_scope");
	    	}*/

//		String quesType = data.get("quesType")==null?"":data.get("quesType").toString();
//		String description =data.get("description")==null?"": data.get("description").toString();
//		Questionnaire entity = new Questionnaire();
//		if(StringUtils.isNotBlank(id)){
//			entity = questionnaireService.findOne(id);
//		}
//		entity.setCreatedBy(userId);
//		entity.setCreatedOrg(orgId);
//		entity.setName(name);
//		entity.setType(quesType);
//		entity.setDescription(description);
//		String answerScopeList = data.get("answerScopeList").toString();
//
//		if(answerScopeList!=null &&JSONArray.parseArray(answerScopeList).size()>0) {
//			String answerScope = UuidUtils.UUID();
//			entity.setAnswerScope(answerScope);
//			this.popUserScopeUtilService.saveScopeData("oa_questionnaire_scope", answerScope, answerScopeList, "oa_questionnaire","answer_scope");
//		}
//		String quesScopeList = data.get("quesScopeList").toString();
//		if(quesScopeList!=null &&JSONArray.parseArray(quesScopeList).size()>0) {
//			String quesScope = UuidUtils.UUID();
//			entity.setQuestionnaireScope(quesScope);
//			this.popUserScopeUtilService.saveScopeData("oa_questionnaire_scope", quesScope, quesScopeList, "oa_questionnaire","questionnaire_scope");
//		}
//	    	Date date = new Date();
//	    	entity.setCreatedDate(date);
//	    	String startDateStr = data.get("startDate")==null?"":data.get("startDate").toString();
//	    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//	    	Date startDate = sdf.parse(startDateStr);
//	    	String endDateStr = data.get("endDate")==null?"":data.get("endDate").toString();
//	    	Date endDate = sdf.parse(endDateStr);
//	    	if(startDate.getTime()> date.getTime()){
//	    		//开始时间大于当前日期问卷未开启
//	    		entity.setStatus("2");
//	    	}
//
//	    	if(startDate.getTime()<= date.getTime()){
//	    		//开始时间大于当前日期问卷开启
//	    		entity.setStatus("1");
//	    	}
//	    	if(endDate.getTime()<= date.getTime()){
//	    		//结束时间小于当前时间问卷关闭
//	    		entity.setStatus("0");
//	    	}
//	    	entity.setStartDate(startDate);
//	    	entity.setEndDate(endDate);
//		entity.setCorpId(corpId);
//		if(StringUtils.isBlank(id)){
//			entity.setPublish(Questionnaire.PublishEnum.NOPUBLISH.getCode());
//		}
//		questionnaireService.save(entity);


		//保存题目选项
	    	List<QuestionnaireTopic> listTopic = new ArrayList<QuestionnaireTopic>();
	    	List<QuestionnaireTopicOptions> listOptions = new ArrayList<QuestionnaireTopicOptions>();
	    	String quesitionnaireId = quesId;
	    	List list = (List) data.get("list");//单选
	    	/*
	    	List sinselect = (List) data.get("sinselect");//单选
	    	List multiselect =  (List) data.get("multiselect");//多选
	    	List check = (List) data.get("check"); //下拉
	    	List fillInBlanks = (List) data.get("fillInBlanks");//填空
	    	List answer = (List) data.get("answer"); //问答
	    	List field =(List) data.get("field"); //附件
	    	List scale = (List) data.get("scale"); //量表
	    	List mulscale = (List) data.get("mulscale"); //矩阵量表
	    	List illustrate = (List) data.get("illustrate"); //说明
	    	List paging = (List) data.get("paging"); //分页
	    	*/
	    	if(list != null && list.size()>0){
	    		for(int i=0;i<list.size();i++){
	    			Map<String,Object> topicMap = (Map<String, Object>) list.get(i);
	    			int topicOrderNo = i+1;

	    			//String topicAllSetting = request.getParameter(topicOrderNo+"sinselect");
	    			List optionSetting = (List) topicMap.get("options");
	    			//Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
	    			topicMap.put("sortNo",topicOrderNo);
	    			QuestionnaireTopic topic = new QuestionnaireTopic();
	    			topic = topicService.getDingSaveTopicInfo(topicMap, quesitionnaireId, (String) topicMap.get("quesType"));
	    			topic.setCreatedBy(userId);
	    			topic.setCreatedOrg(orgId);
	    			topic.setCreatedDate(new Date());
	    			listTopic.add(topic);

	    			List<QuestionnaireTopicOptions> listOption = optionService.getDingSaveOptionsInfo(optionSetting, topic.getId(),userId,orgId);
	    			listOptions.addAll(listOption);
	    		}
	    	}
	    	/*if(multiselect !=null && multiselect.size()>0){
	    		for(int i=0;i<multiselect.size();i++){
	    			String topicOrderNo = (String) multiselect.get(i);
	    			String topicAllSetting = request.getParameter(topicOrderNo+"multiselect");
	    			String optionSetting =request.getParameter(topicOrderNo+"option");
	    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
	    			QuestionnaireTopic topic = new QuestionnaireTopic();
	    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "multiselect");
	    			listTopic.add(topic);
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
	    		}
	    	}
	    	if(check != null && check.size()>0){
	    		for(int i=0;i<check.size();i++){
	    			String topicOrderNo = (String) check.get(i);
	    			String topicAllSetting = request.getParameter(topicOrderNo+"check");
	    			String optionSetting =request.getParameter(topicOrderNo+"option");
	    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
	    			QuestionnaireTopic topic = new QuestionnaireTopic();
	    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "check");
	    			listTopic.add(topic);
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
	    		}
	    	}
	    	if(fillInBlanks !=null && fillInBlanks.size()>0){
	    		for(int i=0;i<fillInBlanks.size();i++){
	    			String topicOrderNo = (String) fillInBlanks.get(i);
	    			String topicAllSetting = request.getParameter(topicOrderNo+"fillInBlanks");
	    			String optionSetting =request.getParameter(topicOrderNo+"option");
	    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
	    			QuestionnaireTopic topic = new QuestionnaireTopic();
	    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "fillInBlanks");
	    			listTopic.add(topic);
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
	    		}
	    	}
	    	if(answer !=null && answer.size()>0){
	    		for(int i=0;i<answer.size();i++){
	    			String topicOrderNo = (String) answer.get(i);
	    			String topicAllSetting = request.getParameter(topicOrderNo+"answer");
	    			String optionSetting =request.getParameter(topicOrderNo+"option");
	    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
	    			QuestionnaireTopic topic = new QuestionnaireTopic();
	    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "answer");
	    			listTopic.add(topic);
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
	    		}
	    	}
	    	if(field !=null && field.size()>0){
	    		for(int i=0;i<field.size();i++){
	    			String topicOrderNo = (String) field.get(i);
	    			String topicAllSetting = request.getParameter(topicOrderNo+"field");
	    			String optionSetting =request.getParameter(topicOrderNo+"option");
	    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
	    			QuestionnaireTopic topic = new QuestionnaireTopic();
	    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "field");
	    			listTopic.add(topic);
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
	    		}
	    	}
	    	if(scale !=null && scale.size()>0){
	    		for(int i=0;i<scale.size();i++){
	    			String topicOrderNo = (String) scale.get(i);
	    			String topicAllSetting = request.getParameter(topicOrderNo+"scale");
	    			String optionSetting =request.getParameter(topicOrderNo+"option");
	    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
	    			QuestionnaireTopic topic = new QuestionnaireTopic();
	    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "scale");
	    			listTopic.add(topic);
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
	    		}
	    	}
	    	if(mulscale != null && mulscale.size()>0){
	    		for(int i=0;i<mulscale.size();i++){
	    			String topicOrderNo = (String) mulscale.get(i);
	    			String topicAllSetting = request.getParameter(topicOrderNo+"mulscale");
	    			String optionSetting =request.getParameter(topicOrderNo+"option");
	    			String optionChildSetting  =request.getParameter(topicOrderNo+"childoption");
	    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
	    			QuestionnaireTopic topic = new QuestionnaireTopic();
	    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "mulscale");
	    			listTopic.add(topic);
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting,optionChildSetting, topic.getId());
	    			listOptions.addAll(listOption);
	    		}
	    	}
	    	if(illustrate !=null && illustrate.size()>0){
	    		for(int i=0;i<illustrate.size();i++){
	    			String topicOrderNo = (String) illustrate.get(i);
	    			String topicAllSetting = request.getParameter(topicOrderNo+"illustrate");
	    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
	    			QuestionnaireTopic topic = new QuestionnaireTopic();
	    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "illustrate");
	    			listTopic.add(topic);
	    		}
	    	}
	    	if(paging !=null && paging.size()>0){
	    		for(int i=0;i<paging.size();i++){
	    			String topicOrderNo = (String) paging.get(i);
	    			String topicAllSetting = request.getParameter(topicOrderNo+"paging");
	    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
	    			QuestionnaireTopic topic = new QuestionnaireTopic();
	    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "paging");
	    			listTopic.add(topic);
	    		}
	    	}*/
	    	List<String> topicList = topicService.getTopicIdByQeusId(quesitionnaireId);
	    	if(topicList != null && topicList.size()>0){
	    		optionService.deleteOptionsByTopicId(topicList);
	    		topicService.deleteTopicByQuesId(quesitionnaireId);
	    	}
	    	topicService.save(listTopic);
	    	optionService.save(listOptions);
	    	questionnaireService.updateQuesMobile(quesId,entity,"1");
		return OperationResult.buildSuccessResult("保存成功");
	}

	/**
	 * 改变问卷状态
	 * @param corpId
	 * @param userId
	 * @param token
	 * @param quesId
	 * @param request
	 * @return
	 */
	@ApiOperation(value="改变问卷状态", notes="改变问卷状态")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "corpId", value = "单位ID", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "token", value = "TOKEN", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "quesId", value = "问卷id", required = true, paramType = "query", dataType = "String"),
	})
	@GetMapping("/getQuestTopic")
	@ResponseBody
	public OperationResult getQuestTopic(@RequestParam("corpId") String corpId,@RequestParam("userId") String userId,@RequestParam("token") String token,@RequestParam("quesId") String quesId,HttpServletRequest request){
		Questionnaire questionnaire = questionnaireService.findOne(quesId);
		return OperationResult.buildSuccessResult(questionnaire);
	}


	@ApiOperation(value="获取统计列表", notes="获取统计列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "corpId", value = "单位ID", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "token", value = "token", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "page", value = "分页页码", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "pageSize", value = "页容量", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "search", value = "搜索内容", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "quesType", value = "问卷类型", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "status", value = "答卷状态", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "startDate", value = "问卷创建时间开始查询时间", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "endDate", value = "问卷创建时间结束查询时间", required = true, paramType = "query", dataType = "String"),
	})
	@GetMapping("/getStatisticsList")
	public OperationResult getStatisticsList(@RequestParam("corpId")String corpId,@RequestParam("userId")String userId,@RequestParam("token") String token,@RequestParam("quesType") String quesType,@RequestParam("status") String status,@RequestParam("startDate") String startDate,@RequestParam("endDate") String endDate,@RequestParam("page") String page,@RequestParam("pageSize") String pageSize,@RequestParam("search") String search,HttpServletRequest request){

		List<Map> list = questionnaireService.getStaticList2Mobile(
				startDate,endDate,quesType,status,search,page,pageSize,userId,corpId,token);
		return OperationResult.buildSuccessResult(list);
	}



	@ApiOperation(value="获取提交人员列表", notes="获取提交人员列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "corpId", value = "单位ID", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "token", value = "token", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "page", value = "分页页码", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "pageSize", value = "页容量", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "search", value = "搜索内容", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "orgId", value = "所属组织", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "isAdmin", value = "是否是管理员", required = true, paramType = "query", dataType = "String"),
	})
	@GetMapping("/getStatisticsPersonList")
	public OperationResult getStatisticsPersonList(@RequestParam("quesId") String quesId,@RequestParam("corpId")String corpId,@RequestParam("userId")String userId,@RequestParam("token") String token,@RequestParam("orgId") String orgId, String endDate,@RequestParam("page") String page,@RequestParam("pageSize") String pageSize,@RequestParam("search") String search,@RequestParam("isAdmin") String isAdmin,HttpServletRequest request){
		List<Map> list = answerService.getStatisticsAnswerList2Mobile(quesId,corpId,userId,search,orgId,page,pageSize,isAdmin,token);
		return OperationResult.buildSuccessResult(list);
	}
	
	/**
	 * 获取未答人员列表
	 * @param quesId
	 * @param corpId
	 * @param userId
	 * @param token
	 * @param page
	 * @param pageSize
	 * @param search
	 * @param orgId
	 * @param request
	 * @return
	 */
	@ApiOperation(value="获取未答人员列表", notes="获取未答人员列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "corpId", value = "单位ID", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "token", value = "token", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "page", value = "分页页码", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "pageSize", value = "页容量", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "search", value = "搜索内容", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "orgId", value = "所属组织", required = true, paramType = "query", dataType = "String"),
	})
	@GetMapping("/getNoAnwserPersonList")
	public OperationResult getNoAnwserPersonList(@RequestParam("quesId") String quesId,@RequestParam("corpId")String corpId,@RequestParam("userId")String userId,@RequestParam("token") String token,@RequestParam("page") String page,@RequestParam("pageSize") String pageSize,@RequestParam("search") String search,@RequestParam("orgId") String orgId,HttpServletRequest request){
		List<Map> list = answerService.getStatisticsNoAnswerInfoMB(quesId,corpId,search,page,pageSize,token,search,orgId);
		return OperationResult.buildSuccessResult(list);
	}

	@ApiOperation(value="获取未答人员id列表", notes="获取未答人员id列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "quesId", value = "问卷Id", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "userName", value = "用户名", required = false, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "departmentName", value = "部门名", required = false, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "token", value = "token", required = true, paramType = "query", dataType = "String")
	})
	@GetMapping("/getStatisticsNoAnswerInfo")
	public OperationResult getStatisticsNoAnswerInfo(@RequestParam("quesId") String quesId,@RequestParam("userName")String userName,@RequestParam("departmentName")String departmentName,@RequestParam("token") String token,HttpServletRequest request){
		List<String> list = answerService.getStatisticsNoAnswerInfo(quesId,userName,departmentName,token);
		return OperationResult.buildSuccessResult(list);
	}

	@ApiOperation(value="问卷回退", notes="问卷回退")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "corpId", value = "单位ID", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "token", value = "token", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "id", value = "问卷答卷id", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "backReason", value = "回退原因", required = true, paramType = "query", dataType = "String"),
	})
	@GetMapping("/quesBack")
	public OperationResult quesBack(@RequestParam("corpId")String corpId,@RequestParam("userId")String userId,
			@RequestParam("token") String token,@RequestParam("id") String id,@RequestParam("backReason") String backReason,
			HttpServletRequest request){
		QusetionnaireAnswerStatus qusetionnaireAnswerStatus = answerStatusService.findOne(id);
		if(qusetionnaireAnswerStatus != null){
			if("2".equals(qusetionnaireAnswerStatus.getStatus()) || "3".equals(qusetionnaireAnswerStatus.getStatus())){
				return OperationResult.buildSuccessResult("回退成功");
			}else{
				answerStatusService.replyQusetionnaireByIds(backReason, Arrays.asList(id));
				//回退问卷推送
				Map<String,Object> map = new HashMap<>();
				Questionnaire questionnaire = questionnaireService.findOne(qusetionnaireAnswerStatus.getQuestionnaireId());
				//问卷名称
				map.put("quesName",questionnaire.getName());
				//问卷结束时间
				map.put("closeDate",questionnaire.getCloseDate());
				map.put("quesId",qusetionnaireAnswerStatus.getQuestionnaireId());
				map.put("userIds",qusetionnaireAnswerStatus.getCreatedBy());
				map.put("type", SendMsgUtils.REPLYSTATUS);
				map.put("backReason", backReason);
				sendMsgUtils.sendMsgToApp(corpId, token, map, request, userId);
				
				String joinIds = "[{\"10\":\"" + qusetionnaireAnswerStatus.getCreatedBy() + "\"}]";
				Map<String,String> paramMap = new HashMap<>();
				paramMap.put("userId", userId);
				paramMap.put("corpId", corpId);
				paramMap.put("token", token);
				paramMap.put("msgTitle", SendMsgUtils.REPLY_FOR_HOA+questionnaire.getName());
				paramMap.put("dataId", UuidUtils.UUID());
				paramMap.put("msgContent", SendMsgUtils.REPLY_FOR_HOA+questionnaire.getName());
				paramMap.put("url", SendMsgUtils.QUES_ANSWER_URL);
				paramMap.put("quesitionnaireId", questionnaire.getId());
				paramMap.put("msgReceiver", joinIds);
				sendMsgUtils.sendMsgToOffice(paramMap);
				return OperationResult.buildSuccessResult("回退成功");
			}
		}
		return OperationResult.buildFailureResult("问卷不存在");
	}

	@ApiOperation(value="问卷回退", notes="问卷回退")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "corpId", value = "单位ID", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "token", value = "token", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "quesId", value = "问卷id", required = true, paramType = "query", dataType = "String"),
	})
	@GetMapping("/getStatistics")
	public OperationResult getStatistics(@RequestParam("corpId")String corpId,@RequestParam("userId")String userId,@RequestParam("token") String token,@RequestParam("quesId") String quesId){
//		questionnaireService.updateQuStatus(questionnaireId,user.getUserId(),user.getCorpId(),user.getJwtToken(),request);
		//答卷数
		int num = answerStatusService.getAnswerNum(quesId, "1");
		//答卷总人数
		int allUser = topicService.getQuestAnswerNum(quesId, token, corpId);
		//答卷总分数
//		double allAnswerScore = answerService.getAllAnswerScore(quesId);
//		//问卷总平均分:答卷总分数/答卷指定范围人数
//		BigDecimal averageScore ;
//		//问卷有效平均分:答卷总分数/答卷人数
//		BigDecimal realAverageScore ;
		Map<String, Object> map = new HashMap<>();
//		if(allUser !=0){
//			averageScore = new BigDecimal(allAnswerScore/allUser);
//			averageScore = averageScore.setScale(2, RoundingMode.HALF_UP);
//			map.put("averageScore", averageScore.toString());
//		}else{
//			map.put("averageScore", "0.00");
//		}
//		if(num !=0){
//			realAverageScore = new BigDecimal(allAnswerScore/num);
//			realAverageScore = realAverageScore.setScale(2, RoundingMode.HALF_UP);
//			map.put("realAverageScore", realAverageScore.toString());
//		}else{
//			map.put("realAverageScore", "0.00");
//		}
		Questionnaire oq = questionnaireService.findOne(quesId);
		List<QuestionnaireTopic> list = topicService.getStatistics(quesId,num,allUser,oq.getType());
		if(!CollectionUtils.isEmpty(list)) {
			for(QuestionnaireTopic questionnaireTopic : list) {
				if(StringUtils.isNotEmpty(questionnaireTopic.getRuleTopicName())) {
					questionnaireTopic.setRuleTopicName(questionnaireTopic.getRuleTopicName().replace("<br/>", "\n"));
					questionnaireTopic.setRuleTopicName(questionnaireTopic.getRuleTopicName().replace("&nbsp;", " "));
				}
			}
		}
		map.put("topicSetting", list);
		String titleSetting = StringUtils.null2String(oq.getTitleSetting());
		if(!"".equals(titleSetting)){
			Map<String, Object> mapSetting = new HashMap<String, Object>();
			mapSetting = JsonUtils.readValue(titleSetting);
			map.put("titleSetting", mapSetting);
		}else{
			map.put("titleSetting", titleSetting);
		}
		map.put("entity", oq);
		map.put("topicAnswerNum", num);
		return OperationResult.buildSuccessResult(map);
	}


	/**
	 * 特殊题型详情数据查询
	 * @param corpId
	 * @param userId
	 * @param token
	 * @param quesId
	 * @param topicType
	 * @param topicId
	 * @return
	 */
	@ApiOperation(value="特殊题型详情数据查询", notes="特殊题型详情数据查询")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "corpId", value = "单位ID", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "token", value = "token", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "quesId", value = "问卷id", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "topicType", value = "问卷类型", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "topicId", value = "问卷题型", required = true, paramType = "query", dataType = "String"),
	})
	@GetMapping("/getOptionDetail")
	public OperationResult getOptionDetail(@RequestParam("corpId")String corpId,@RequestParam("userId")String userId,@RequestParam("token") String token,@RequestParam("quesId") String quesId,@RequestParam("topicType")String topicType,@RequestParam("topicId")String topicId){

		List<Map> list = answerService.getAnswerDetail(quesId,topicType,topicId,token,corpId);
		return OperationResult.buildSuccessResult(list);
	}

	/**
	 * 获取回退原因
	 * @param id
	 * @param request
	 * @return
	 */
	@ApiOperation(value="获取回退原因", notes="获取回退原因")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "corpId", value = "单位ID", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "token", value = "token", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "String"),
	})
	@RequestMapping(value="/getBackReason", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    public OperationResult getBackReason(@RequestParam("id") String id, HttpServletRequest request) {
		QusetionnaireAnswerStatus qas = answerStatusService.findOne(id);
		return OperationResult.buildSuccessResult(qas.getBackReason());
    }
	
	/**
	 * 获取成绩排名
	 * @param request
	 * @return
	 */
	@ApiOperation(value="获取成绩排名", notes="获取成绩排名")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "corpId", value = "单位ID", required = true, paramType = "query", dataType = "String"),
		@ApiImplicitParam(name = "token", value = "token", required = true, paramType = "query", dataType = "String"),
		@ApiImplicitParam(name = "page", value = "分页页码", required = true, paramType = "query", dataType = "String"),
    	@ApiImplicitParam(name = "pageSize", value = "页容量", required = true, paramType = "query", dataType = "String"),
		@ApiImplicitParam(name = "quesId", value = "问卷id", required = true, paramType = "query", dataType = "String"),
	})
	@RequestMapping(value="/getRankingList", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    public OperationResult getRankingList(@RequestParam("quesId") String quesId,@RequestParam("page") String page,@RequestParam("pageSize") String pageSize,@RequestParam("corpId") String corpId,@RequestParam("token") String token,HttpServletRequest request) {
		List<Map> map = answerStatusService.getDingRankingList(quesId, page, pageSize, corpId, token);
		return OperationResult.buildSuccessResult("获取成绩排名列表成功", map);
    }
	
	/**
	 * 获取问卷提示窗数据
	 * @param request
	 * @return
	 */
	@ApiOperation(value="获取问卷提示窗数据", notes="获取问卷提示窗数据")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "corpId", value = "单位ID", required = true, paramType = "query", dataType = "String"),
		@ApiImplicitParam(name = "token", value = "token", required = true, paramType = "query", dataType = "String"),
		@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "String"),
	})
	@RequestMapping(value="/getQuesWindowMsg", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    public OperationResult getQuesWindowMsg(@RequestParam("userId") String userId,@RequestParam("corpId") String corpId,@RequestParam("token") String token,HttpServletRequest request) {
		Map<String,Object> reMap= questionnaireService.getWindowMsg(userId, corpId, token, request);
		return OperationResult.buildSuccessResult("获取成功", reMap);
    }
}
	 	
	 	
